# Copyright [2011] [Ilya Rudakov]
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import os
from job_manager.utils.code_gen import CodeGenerator

__author__ = 'irudakov'

def handle_java_job(job_path, job_name):
    handle_java_settings(job_path)
    handle_java_log4j_properties(job_path, job_name)

def handle_java_log4j_properties(job_path, job_name):
    config_path = job_path + "/config/log4j.properties"
    config_file = open(config_path, "r")

    result = []
    for line in config_file:
        if line.startswith("log4j.appender.file.File"):
            result.append("log4j.appender.file.File=%s\n" % os.path.abspath(job_path + "/logs/%s.log" % job_name))
            continue
        result.append(line)
    config_file.close()

    config_file = open(config_path, "w")
    config_file.writelines(result)
    config_file.close()

def handle_java_settings(job_path):
    f_settings = open(job_path + "/settings.py", "w")
    code_gen = CodeGenerator()
    code_gen.begin(tab = "    ")
    code_gen.write("SETTINGS = {")
    code_gen.newline()
    code_gen.indent()
    code_gen.write("'classpath':'%s/lib'," % os.path.abspath(job_path))
    code_gen.newline()
    code_gen.write("'config_path':'%s/config'," % os.path.abspath(job_path))
    code_gen.newline()
    code_gen.dedent()
    code_gen.write("}")

    f_settings.write(code_gen.end())
    f_settings.close()
    del code_gen